package com.hex.ds.hdrs.common.utils;

import java.net.*;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

/**
 * @Package: com.hex.ds.hdrs.common.utils
 * @ClassName IpAddressUtil
 * @Description: 获取当前主机IP工具类
 * @Author: wz.li
 * @Date 2023/2/27 14:39
 * @Version v2.0.2
 **/
public class IpAddressUtil {

    /*
     * @Method: getIpAddressString <br>
     * @Param: [] <br>
     * @Return: java.lang.String <br> 
     * @Description：获取当前主机局域网IP<br>
     * @Author： wz.li<br>
     * @Date： 2023/2/27 14:39 <br>
     * @Version： V2.0.2<br>
     */
    public static String getIpAddressString() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    /*
     * @Method: getIpAddress <br>
     * @Param: [] <br>
     * @Return: java.util.List<java.lang.String> <br> 
     * @Description：获取全部 IPV4/IPV6 IP地址<br>
     * @Author： wz.li<br>
     * @Date： 2023/2/27 14:39 <br>
     * @Version： V2.0.2<br>
     */
    public static List<String> getIpAddress() throws SocketException {
        List<String> list = new LinkedList<>();
        Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface network = (NetworkInterface) enumeration.nextElement();
            if (network.isVirtual() || !network.isUp()) {
                continue;
            } else {
                Enumeration addresses = network.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = (InetAddress) addresses.nextElement();
                    if (address != null && (address instanceof Inet4Address || address instanceof Inet6Address)) {
                        list.add(address.getHostAddress());
                    }
                }
            }
        }
        return list;
    }

    /*
     * @Method: getIpAddress2 <br>
     * @Param: [] <br>
     * @Return: java.util.List<java.lang.String> <br> 
     * @Description：获取全部存放本机IP地址<br>
     * @Author： wz.li<br>
     * @Date： 2023/2/27 14:39 <br>
     * @Version： V2.0.2<br>
     */
    public static List<String> getIpAddress2() throws SocketException {
        List<String> list = new LinkedList<>();
        Enumeration enumeration = NetworkInterface.getNetworkInterfaces();
        while (enumeration.hasMoreElements()) {
            NetworkInterface network = (NetworkInterface) enumeration.nextElement();
            Enumeration addresses = network.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress address = (InetAddress) addresses.nextElement();
                if (address != null && (address instanceof Inet4Address || address instanceof Inet6Address)) {
                    list.add(address.getHostAddress());
                }
            }
        }
        return list;
    }
}
